package com.cloudkinto.service.message.impl;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloudkinto.common.common.DateUtils;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.utils.ExcelUtils;
import com.cloudkinto.entity.MessageNoticeDo;
import com.cloudkinto.dao.MessageNoticeDao;
import com.cloudkinto.service.message.MessageNoticeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import com.cloudkinto.extentity.message.MessageNoticeDto;
import com.cloudkinto.service.message.exportVo.MessageNoticeExportVo;
import com.cloudkinto.service.storage.StorageService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 *  service实现类
 * </p>
 * @author hua
 * @since 2023-08-10
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class MessageNoticeServiceImpl extends ServiceImpl<MessageNoticeDao, MessageNoticeDo> implements MessageNoticeService {
    @Autowired
    private MessageNoticeDao dao;
    @Autowired
    private StorageService storageService;

    @Override
    public SingleResult addInit() {
        return SingleResult.success("");
    }

    @Override
    public Object add(Object req, Long userId) {
        MessageNoticeDo entityDo = new MessageNoticeDo();
        BeanUtils.copyProperties(req, entityDo);
        handlerAddBefore(entityDo, userId);
        dao.insert(entityDo);
        return handlerAddAfter(entityDo);
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(MessageNoticeDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(MessageNoticeDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success("");
    }

    @Override
    public Object update(Object req, Long userId) {
        /*MessageNoticeDo entityDo = dao.selectById(req.getId());
        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
        return handlerUpdateAfter(entityDo);*/
        return null;
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(MessageNoticeDo entityDo, Long userId) {
        entityDo.setUpdateBy(userId);
        entityDo.setUpdateTime(new Date());
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(MessageNoticeDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        MessageNoticeDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(MessageNoticeDo entityDo, Long userId) {
        entityDo.setDeleteBy(userId);
        entityDo.setDeleteTime(new Date());
    }

    @Override
    public Object detail(Long id) {
        MessageNoticeDo entityDo =  dao.selectById(id);
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return handlerDetailAfter(res);
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        Map<String, Object> result = new HashMap<>();
        result.put("storageList", storageService.getStorageList());
        return SingleResult.success("");
    }

    @Override
    public List<MessageNoticeDto> getList(Map<String, String> map) {
        return null;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        IPage<MessageNoticeDto> page = pageInit(map);
        List<MessageNoticeDto> list = dao.getListPage(page, map);
//        List<MessageNoticeDto> resList = handlerListAfter(list);
        PageResult result = new PageResult(list, (int)page.getCurrent(), (int)page.getSize(), (int)page.getTotal(), (int)page.getPages());
        return result;
    }

    //查询分页列表之后对列表数据的处理
    private List<MessageNoticeDto> handlerListAfter(List<MessageNoticeDto> list ){
        List<MessageNoticeDto> result = new ArrayList<>();
        for (MessageNoticeDto et : list) {
            MessageNoticeDto res = new MessageNoticeDto();
            BeanUtils.copyProperties(et, res);
            result.add(res);
        }
        return result;
    }

    private IPage<MessageNoticeDto> pageInit(Map<String, String> map) {
        IPage<MessageNoticeDto> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<MessageNoticeDo> queryBuild(Map<String, String> map) {
        QueryWrapper<MessageNoticeDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.like("keyword", map.get("keyword"));
        }
        return wrapper;
    }

    @Override
    public void markDeal(Long id, Long userId) {
        MessageNoticeDo et = dao.selectById(id);
        if (et == null) {
            throw new BizException(SysConstant.No_Data);
        }
        if (et.getStatus() == 1) {
            return;
        }
        et.setStatus(1);
        et.setUpdateBy(userId);
        et.setUpdateTime(new Date());
        dao.updateById(et);
    }


    @Override
    public void noticeAdd(String type, Long thirdId, String title, String content, Long userId, Long companyId) {
        this.noticeAdd("rack", type, thirdId, title, content, userId, companyId);
    }


    @Override
    public void noticeAdd(String module, String type, Long thirdId, String title, String content, Long userId, Long companyId) {
        //判断 有没有未处理的 相同模块 类型
        int count = dao.getCountBeforeAdd(module, type, thirdId);
        if (count > 0) {
            return;
        }
        MessageNoticeDo et = new MessageNoticeDo();
        et.setModule(module);
        et.setMessageType(type);
        et.setThirdId(thirdId);
        et.setMessageTitle(title);
        et.setMessageContent(content);
        et.setCreateBy(userId);
        et.setCreateTime(new Date());
        et.setDeleteFlag(0);
        et.setCompanyId(companyId);
        et.setStatus(0);
        dao.insert(et);
    }


    @Override
    public int getRackUnDealCount() {
        int count = dao.selectCount(new LambdaQueryWrapper<MessageNoticeDo>()
                .eq(MessageNoticeDo::getModule, "rack").eq(MessageNoticeDo::getStatus, 0));
        return count;
    }


    @Override
    public void exportRackNotice(Map<String, String> map, HttpServletResponse response) {
        map.put("module", "rack");
        List<MessageNoticeDto> list = dao.getListPage(map);

        List<MessageNoticeExportVo> exportVoList = new ArrayList<>();
        for (MessageNoticeDto et : list) {
            MessageNoticeExportVo exportVo = new MessageNoticeExportVo();
            BeanUtils.copyProperties(et, exportVo);
            exportVoList.add(exportVo);
        }

        try {
            ExcelUtils.exportExcel(exportVoList, MessageNoticeExportVo.class, "异常库位", new ExportParams(), response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
